//
//  MYGBaseInfoController.swift
//  MYDoctor
//
//  Created by chenjs on 2024/4/27.
//

import UIKit
import IQKeyboardManagerSwift
import BRPickerView

class MYGBaseInfoController: MYGBaseController {
    private var hosArr:[String] = []
    private var keshiArr:[String] = []
    private var contents:[Any] = []
    var image: UIImage?
    var model : MYGUserModel =  MYGUserManager.getUser()!
    override func viewDidLoad() {
        super.viewDidLoad()
        configCell()
        configUI()
        getHosAndSub()
    }
    
    // MARK: - Cell
    func configCell() {
        var items: [Any] = []
        
        let image = MYGChangeEnterMessageImageCellModel()
        //image.image = UIImage(named: "\(model.doctor.avatar)")
        items.append(image)
        
        let nameItem = MYGChangeEnterMessageTextCellModel()
        nameItem.name = "姓名"
        nameItem.placeholder = "请输入姓名"
        nameItem.content = model.doctor.name
        nameItem.isRequeired = true
        items.append(nameItem)
        
//        let niceItem = MYGChangeEnterMessageTextCellModel()
//        niceItem.name = "用户名"
//        niceItem.placeholder = "请输入用户名"
//        niceItem.content = model.doctor.nickname
//        niceItem.isRequeired = false
//        items.append(niceItem)
        
        let sexItem = MYGChangeEnterMessageTextCellModel()
        sexItem.name = "性别"
        sexItem.placeholder = "请选择性别"
        sexItem.content = model.doctor.gender == 1 ? "男" :(model.doctor.gender == 2 ? "女" : "")
        sexItem.isRequeired = true
        sexItem.canEdit = false
        sexItem.clickAction = {[weak sexItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = sexItem, let self = self else {
                return
            }
            BRStringPickerView.showPicker(withTitle: "请选择身份", dataSourceArr: ["男","女"], select: 0) {[self] item in
                dateItem.content = item?.value ?? ""//性别 1男 2女
                self.model.doctor.gender = item?.value == "男" ? 1 : 2
                self.tableView.reloadData()
 
            }
        }
        items.append(sexItem)
        
        let contactItem = MYGChangeEnterMessageTextCellModel()
        contactItem.name = "手机号"
        contactItem.placeholder = "请输入手机号"
        contactItem.content = "\(model.doctor.phone)"
        contactItem.isRequeired = true
        items.append(contactItem)
        
        let idItem = MYGChangeEnterMessageTextCellModel()
        idItem.name = "身份"
        idItem.placeholder = "请选择身份"
        idItem.isRequeired = true
        idItem.canEdit = false
        idItem.content = model.doctor.identity
        idItem.clickAction = {[weak idItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = idItem, let self = self else {
                return
            }
            BRStringPickerView.showPicker(withTitle: "请选择身份", dataSourceArr: ["医生","医助"], select: 0) {[self] item in
                dateItem.content = item?.value ?? ""//普通0 医助1 科室2
                self.model.doctor.hospital = item?.value ?? ""
                self.tableView.reloadData()
 
            }
        }
        items.append(idItem)

        let hospitalItem = MYGChangeEnterMessageTextCellModel()
        hospitalItem.name = "所在医院"
        hospitalItem.placeholder = "请输入所在医院"
        hospitalItem.isRequeired = true
        hospitalItem.canEdit = false
        hospitalItem.content = model.doctor.hospital
        hospitalItem.clickAction = {[weak hospitalItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = hospitalItem, let self = self else {
                return
            }
            let vc = MYGHospitalViewController()
            vc.callHospitailName = {name in
                dateItem.content = name
                self.tableView.reloadData()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        items.append(hospitalItem)
        
        let dateItem = MYGChangeEnterMessageTextCellModel()
        dateItem.name = "科室"
        dateItem.placeholder = "请输科室名称"
        dateItem.content = model.doctor.department
        dateItem.canEdit = false
        dateItem.isRequeired = true
        dateItem.clickAction = {[weak dateItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = dateItem, let self = self else {
                return
            }
            BRStringPickerView.showPicker(withTitle: "请选择科室", dataSourceArr: self.keshiArr, select: 0) {[self] item in
                dateItem.content = item?.value ?? ""
                self.model.doctor.department =  item?.value ?? ""
                self.tableView.reloadData()
 
            }
        }
        items.append(dateItem)
        
        let reItem = MYGChangeEnterMessageTextCellModel()
        reItem.name = "职称"
        reItem.placeholder = "请选择职称"
        reItem.content = model.doctor.title
        reItem.canEdit = false
        reItem.isRequeired = true
        reItem.clickAction = {[weak reItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = reItem, let self = self else {
                return
            }
            BRStringPickerView.showPicker(withTitle: "请选择职称", dataSourceArr: ["主任医师","副主任医师","主治医师","住院医师","医生助理"], select: 0) {[self] item in
                dateItem.content = item?.value ?? ""
                self.model.doctor.title =  item?.value ?? ""
                self.tableView.reloadData()
 
            }
        }
        items.append(reItem)
        
        let emailItem = MYGChangeEnterMessageTextCellModel()
        emailItem.name = "通讯地址"
        emailItem.placeholder = "请输入通讯地址"
        emailItem.content = model.doctor.city
        emailItem.isRequeired = false
        items.append(emailItem)

        let addressItem = MYGChangeEnterMessageTextCellModel()
        addressItem.name = "详细地址"
        addressItem.placeholder = "请输入详细地址"
        addressItem.content = model.doctor.address
        addressItem.isRequeired = false
        items.append(addressItem)
        
        contents = items
        tableView.reloadData()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "基本信息"
        
        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(saveButton)
        saveButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(bottomSafeheight)
            make.height.equalTo(49)
        }
        tableView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(saveButton.snp.top)
        }
     
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: MYGChangeEnterMessageImageCell.self)
        tableView.register(cellWithClass: MYGInfoTitleTableViewCell.self)
        return tableView
    }()
    
    private lazy var saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(17)
        //btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        btn.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
        return btn
    }()
}
extension MYGBaseInfoController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        65
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let item = contents[indexPath.row] as? MYGChangeEnterMessageImageCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGChangeEnterMessageImageCell.self, for: indexPath)
            cell.model = item
            return cell
        }
            
        if let item = contents[indexPath.row] as? MYGChangeEnterMessageTextCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGInfoTitleTableViewCell.self, for: indexPath)
            cell.model = item
            return cell
        }
   
        return UITableViewCell()
    }
    
}
extension MYGBaseInfoController {
    
    @objc func nextAction() {
        
        if let model = contents.first as? MYGChangeEnterMessageImageCellModel, let image = model.image {
            MYGLoading.show()
            MMYGNetwork<MYGCommonAPI, MYGEmptyModel>.request(target: .uploadOssFiles(image: image)) { _ in
                MYGLoading.hide()
            } stringBlock: { text in
                self.requestMessage(avar: text)
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }

        } else {
            requestMessage(avar: "")
        }
    }
    
    func requestMessage(avar:String){
        var params:[String:Any] = [:]
        for (index, item) in contents.enumerated() {
            if let item = item as? MYGChangeEnterMessageTextCellModel {
                if item.isRequeired && item.content.isEmpty {
                    MMYGHUD.showToast(text: "请将信息填写完整")
                    return
                }
                
                if item.content.isEmpty {
                    continue
                }
                
                switch index {
                case 1:
                    params["name"] = item.content
                case 2:
                    params["gender"] = item.content == "女" ? 2 : 1
                case 3:
                    params["phone"] = item.content
                case 4:
//                    var str = "2"
//                    if item.content == "医生" {
//                        str = "0"
//                    }else if (item.content == "医助") {
//                        str = "1"
//                    }
                    params["identity"] = item.content  //普通0 医助1 科室2
                case 5:
                    params["hospital"] = item.content
                case 6:
                    params["department"] = item.content
                case 7:
                    params["title"] = item.content
                case 8:
                    params["city"] = item.content
                case 9:
                    params["address"] = item.content
                default:
                    break
                }
                
            }
        }
        if !avar.isEmpty{
            params["avatar"] = avar
        }
        params["idNumber"] = self.model.doctor.idNumber
        
        MYGLoading.show()
        MMYGNetwork<MYGRegisterAPI,MYGEmptyModel>.request(target: .uploadDoctorInf(id:"\(model.doctor.id)",params: params)) { _  in
            self.getDoctorInfo()
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getDoctorInfo(){
        let phone = MYGUserManager.getUser()?.doctor.phone ?? 0
        MMYGNetwork<MYGMicrosrationApi,MYGUserDoctor>.request(target: .get_doctor_phone_info(phone: "\(phone)")) { model  in
            MYGLoading.hide()
            guard let item = model else {return}
            
            let user = MYGUserManager.getUser()
            user?.doctor = item
            MYGUserManager.saveUser(user!)
            
            let vc = MYGUpdateInfoViewController()
            vc.model = user
            self.navigationController?.pushViewController(vc)
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    
    
    func getHosAndSub(){
        
        MMYGNetwork<MYGResumeApi, MYGSubjectListModel>.request(target: .getSubjectList(params: [:])) {[weak self] result in
            guard let items = result?.data else {
                return
            }
            for item in items {
                self?.keshiArr.append(item.label)
            }
        } failed: { _, error in
//            MYGLoading.hide()
//            MYGHUD.showToast(text: error)
        }
    }
}
